package cn.wowjoy.pda.android_pharmacy.ui.activity.door.put;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

import cn.wowjoy.pda.android_pharmacy.R;
import cn.wowjoy.pda.android_pharmacy.common.core.BaseActivity;
import cn.wowjoy.pda.android_pharmacy.common.utils.Contants;
import cn.wowjoy.pda.android_pharmacy.common.utils.NetWorkUtils;
import cn.wowjoy.pda.android_pharmacy.common.utils.PreferenceManager;
import cn.wowjoy.pda.android_pharmacy.common.widget.CreateDialog;
import cn.wowjoy.pda.android_pharmacy.common.widget.MDialog;
import cn.wowjoy.pda.android_pharmacy.common.widget.MyToast;
import cn.wowjoy.pda.android_pharmacy.databinding.ActivityDoorPutScanBinding;
import cn.wowjoy.pda.android_pharmacy.model.xmlEntity.putInfo.PutSingleBeen;
import cn.wowjoy.pda.android_pharmacy.mvvm.presenter.DoorPutScanPresenter;
import cn.wowjoy.pda.android_pharmacy.mvvm.vm.DoorPutScanViewModel;
import cn.wowjoy.pda.android_pharmacy.ui.activity.hospital.put.InHospitalPutHandActivity;

public class DoorPutScanActivity extends BaseActivity<ActivityDoorPutScanBinding, DoorPutScanViewModel, DoorPutScanPresenter> implements View.OnClickListener, DoorPutScanPresenter.OnSubmitHospitalResult {
    //上架单总数量 --种类
    public  float TOTAL_NUM = Integer.parseInt(PreferenceManager.getInstance().getDoorPutProgressTotal());
    //当前进度条
    private  float countAlready=0;
    private MDialog failSubmit;
    private MDialog mDialog;
    private List<String> mStrings;
    private MDialog mFailDialog;
    //PDA扫码广播
    private ScanReceiver mScanReceiver;
    private IntentFilter intentFilter;
    public static final int UPDATE_PROGRESS = 1;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_PROGRESS:
                    if(null != mDialog){
                        CreateDialog.dismiss(DoorPutScanActivity.this);
                        mDialog.cancel();
                    }

                    if (countAlready < TOTAL_NUM) {
                        countAlready++;
                    }
                    if (countAlready == TOTAL_NUM) {
                        //扫码完成
                        binding.rlImgvScan.setVisibility(View.GONE);
                        binding.rlVoice.setVisibility(View.VISIBLE);
                        binding.btCheckProgressSureSuccess.setVisibility(View.VISIBLE);
                        binding.tvPutDetailTitle.titleBackLl.setVisibility(View.GONE);
                        binding.tvPutDetailTitle.titleMenuConfirm.setVisibility(View.GONE);
                        binding.progressScanGet.setProgress(100);
                        //检查是否所有都OK了
                        if (viewModel.checkTotal()) {
                            binding.btCheckProgressSureSuccess.setEnabled(true);
                            binding.btCheckProgressSureSuccess.setBackgroundColor(getResources().getColor(R.color.background_main));
                        }
                    }
                    updateFirstUI();
                    break;
            }
        }
    };

    @Override
    protected void init(Bundle savedInstanceState) {
        binding.setPresenter(presenter);
        binding.setViewModel(viewModel);
        binding.tvPutDetailTitle.titleTextTv.setText("药品上架");
        binding.tvPutDetailTitle.titleBackLl.setVisibility(View.VISIBLE);
        binding.tvPutDetailTitle.titleBackTv.setText("上架单详情");
        binding.medicineIdScanGet.setText(presenter.DJJLID);
        binding.tvPutDetailTitle.titleMenuConfirm.setVisibility(View.VISIBLE);
        binding.tvPutDetailTitle.titleMenuConfirm.setText("手动上架");
        binding.tvPutDetailTitle.titleMenuConfirm.setTextColor(getResources().getColor(R.color.white));
        binding.tvPutDetailTitle.titleMenuConfirm.setOnClickListener(this);
        //TODO:PDA扫码广播的接收跳转
        mScanReceiver = new ScanReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction(Contants.WOW_NEW_ADD);
        binding.tvPutDetailTitle.titleBackLl.setOnClickListener(this);
        binding.btCheckProgressSureSuccess.setOnClickListener(this);
        binding.imgv123.setOnClickListener(this);
        presenter.registeOnSubmitResultListener(this);
        updateFirstUI();
    }
    /**
     *  根据唯一ID 查找是否存在
     * @param stringExtra
     */
    public void checkExist(String stringExtra) {
        PutSingleBeen putBeen = viewModel.checkExist(stringExtra);
        if( null == putBeen){
            // 扫码错误
            CreateDialog.failDialog(DoorPutScanActivity.this);
            return;
        }
//        Log.e("checkExist1", "checkExist: "+viewModel.mMoveBaens.toString());
//        Log.e("checkExist2", "checkExist: "+putBeen.toString() );
        if(putBeen.isPut()){
            CreateDialog.failDialog3(DoorPutScanActivity.this,"上架错误","该药品已上架完，请人工复核");
            return;
        }
        Intent intent=new Intent(DoorPutScanActivity.this ,DoorPutProgressActivity.class);
        intent.putExtra("check",putBeen);
        startActivityForResult(intent, Contants.REQUEST_CODE_NEXT);
    }
    //TODO:界面药品信息的更新
    private void updateFirstUI() {
        countAlready=viewModel.calcNum();
        binding.tvProgressScanGet.setText((int)countAlready + "/" + (int)TOTAL_NUM);
        //设置进度条
        binding.progressScanGet.setProgress((int)((countAlready /TOTAL_NUM)*100));
        if (countAlready == TOTAL_NUM) {
            //8/8 BACK回去的
            binding.rlImgvScan.setVisibility(View.GONE);
            binding.rlVoice.setVisibility(View.VISIBLE);
            binding.btCheckProgressSureSuccess.setVisibility(View.VISIBLE);
            binding.tvPutDetailTitle.titleBackLl.setVisibility(View.GONE);
            binding.tvPutDetailTitle.titleMenuConfirm.setVisibility(View.GONE);
            binding.progressScanGet.setProgress(100);
            //检查是否所有都OK了
            if (viewModel.checkTotal()) {
                binding.btCheckProgressSureSuccess.setEnabled(true);
                binding.btCheckProgressSureSuccess.setBackgroundColor(getResources().getColor(R.color.background_main));
            }
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mScanReceiver, intentFilter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(mScanReceiver);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        CreateDialog.dismiss(DoorPutScanActivity.this);
        if(null != mDialog){
            mDialog.cancel();
        }
        if(null != failSubmit){
            failSubmit.cancel();
        }
    }
    @Override
    public void onBackPressed() {
        //药单未完成  BACK键返回  每次要把当前展示的加到集合中
        Intent intent = new Intent();
        intent.putExtra("currently", viewModel.mMoveBaens);
//        Log.e("onBackPressed" , "onBackPressed: "+  viewModel.mMoveBaens.size());
        setResult(Contants.REQUEST_BACK_CODE, intent);
        super.onBackPressed();
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_door_put_scan;
    }

    @Override
    protected Class<DoorPutScanPresenter> getPresenterClass() {
        return DoorPutScanPresenter.class;
    }

    @Override
    protected Class<DoorPutScanViewModel> getViewModelClass() {
        return DoorPutScanViewModel.class;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case Contants.REQUEST_CODE:
                //手动审核的结果
                switch (resultCode){
                    case Contants.RESULT_HAND_SUCCESS_CODE:
                        PutSingleBeen check = (PutSingleBeen) data.getExtras().getSerializable("check");
//                        Log.e("TAG", "onActivityResult: "+check.toString() );
                        //手动审核的药 有并且还没被核对过
                        if(viewModel.checkSecond(check)){
                            mDialog = CreateDialog.successDialog(DoorPutScanActivity.this, 6 ,"上架成功");
                            mHandler.sendEmptyMessageDelayed(UPDATE_PROGRESS,800);
                            return;
                        }
                        //手动审核的药 有但是已经被核对过了
                        CreateDialog.failDialog3(DoorPutScanActivity.this,"上架错误","该药品已上架完，请人工复核");
                        break;
                    case Contants.RESULT_HAND_FAIL_CODE:

                        break;
                }
                break;
            case Contants.REQUEST_CODE_NEXT:
                //扫码审核页面成功
                switch (resultCode){
                    case Contants.RESULT_SUCCESS_CODE:
                        PutSingleBeen check = (PutSingleBeen) data.getExtras().getSerializable("check");
                        viewModel.checkSecond(check);
                        mDialog = CreateDialog.successDialog(DoorPutScanActivity.this, 6 ,"上架成功");
                        mHandler.sendEmptyMessageDelayed(UPDATE_PROGRESS,800);
                        break;
                    case Contants.RESULT_FAIL_CODE:

                        break;
                }
                break;
        }
    }
    @Override
    public void onClick(View v) {
         switch (v.getId()){
            case R.id.title_back_ll:
                Intent intent = new Intent();
                intent.putExtra("currently", viewModel.mMoveBaens);
                setResult(Contants.REQUEST_BACK_CODE, intent);
                finish();
                break;
            case R.id.bt_check_progress_sure_success:
                //检查   更新住院取完药接口
                if(NetWorkUtils.isWifi(DoorPutScanActivity.this)){
                    presenter.update("1",PreferenceManager.getInstance().getLUserId());
                }else{
                    CreateDialog.failDialog3(DoorPutScanActivity.this,"错误","当前网络不可用，请检查你的网络设置");
                }
                break;
            case R.id.imgv123:
                //测试  模拟扫码枪
//                checkExist(mStrings.remove(0));
//                presenter.update("1",PreferenceManager.getInstance().getLUserId());
                break;
             case R.id.title_menu_confirm:
                 //跳转至手动审核
                 ArrayList<PutSingleBeen> unCheckBeens = viewModel.handCheck(viewModel.mMoveBaens);
                 if(null != unCheckBeens && unCheckBeens.size() >0 ){
                     Intent intent2 = new Intent(DoorPutScanActivity.this, InHospitalPutHandActivity.class);
                     intent2.putExtra("total", unCheckBeens);
                     startActivityForResult(intent2,Contants.REQUEST_CODE);
                 }else{
                     new MyToast(DoorPutScanActivity.this).showinfo("已审核完");
                 }
                 break;
        }
    }

    //上架更新成功
    @Override
    public void submitSuccess() {
        new MyToast(this).showinfo("上架成功");
        startActivity(new Intent(DoorPutScanActivity.this, DoorPutIndexActivity.class));
    }
    //上架更新失败
    @Override
    public void submitFail(String errMsg) {
//        new MyToast(this).showinfo(errMsg);
        failSubmit = CreateDialog.failSubmit(DoorPutScanActivity.this, "上架失败", "该取药单已有其他人上架完成，请重新确认", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(DoorPutScanActivity.this, DoorPutIndexActivity.class));
                finish();
            }
        });
    }
    //TODO:接收PDA扫码广播，准备跳转
    class ScanReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()){
                case Contants.WOW_NEW_ADD:
                    String stringExtra = intent.getStringExtra(Contants.WOW_NEW_KEY);
//                    new MyToast(DoorPutScanActivity.this).showinfo("扫到的是: "+stringExtra);
//                    Log.e("onReceive1: ", remove.toString());
                    checkExist(stringExtra);
                    break;
            }
        }
    }
}
